package personal.shin.smsviewer;

import java.io.InputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.format.DateUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class SMSViewer  extends Activity implements OnGestureListener{
   
    /* implement Animation */
    ViewFlipper flipper;
    
    private void shiftToRight()
    {
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
        		R.anim.push_left_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
        		R.anim.push_left_out));
        flipper.showNext();
    }
    
    private void shiftToLeft()
    {
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
        		R.anim.push_right_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
        		R.anim.push_right_out));
        flipper.showNext();
    }    
    
    /* handle gesture input */
 
    private GestureDetector gestureScanner;
    
    private static final int SWIPE_MIN_DISTANCE = 50;
    private static final int SWIPE_MAX_OFF_PATH = 500;
    private static final int SWIPE_THRESHOLD_VELOCITY = 5;
    
    @Override
    public boolean onTouchEvent(MotionEvent me) {
        return gestureScanner.onTouchEvent(me);
    }
 
    public boolean onDown(MotionEvent e) {
        return true;
    }
    
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	showPage(NEXT);                
            }
            // left to right swipe
            else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	showPage(PREVIOUS);                     
            }
            // down to up swipe
            else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Swipe up",
                        Toast.LENGTH_SHORT).show();
            }
            // up to down swipe
            else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Swipe down",
                        Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            
        }
 
        return true;
    }
 
    public void onLongPress(MotionEvent e) {
    	showPage(NEXT);          
    }
 
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return true;
    }
 
    public void onShowPress(MotionEvent e) {
    }
 
    public boolean onSingleTapUp(MotionEvent e) {;    	
    	showPage(PREVIOUS);     	
        return true;
    }
    /* Two pages */
    private SMSPage oddPage;
    private SMSPage evenPage;
    
    private SMSPage getCurrentPage() 
    {
    	if(oddPage.isCurrent() == true)
    	{
    		return oddPage;
    	}   
    	else
    	{
       		return evenPage;    		
    	}
    }

    private SMSPage goToNextPage() 
    {
    	if(oddPage.isCurrent() == true)
    	{
    		evenPage.setCurrent(true);
    		oddPage.setCurrent(false);    		
    		return evenPage;
    	}    	
    	oddPage.setCurrent(true);
    	evenPage.setCurrent(false);    		
		return oddPage;
    }

    private void initializePages() {
    	oddPage = new SMSPage(
    			(ProfileImageView)findViewById(R.id.profile_pic1),
    			(TextView)findViewById(R.id.Order1),
    			(TextView)findViewById(R.id.Date1),
    			(TextView)findViewById(R.id.Sender1),
    			(TextView)findViewById(R.id.Body1));
    	oddPage.setProfileImageColor(getString(R.string.top_background));
    	evenPage = new SMSPage(
    			(ProfileImageView)findViewById(R.id.profile_pic2),
    			(TextView)findViewById(R.id.Order2),
    			(TextView)findViewById(R.id.Date2),
    			(TextView)findViewById(R.id.Sender2),
    			(TextView)findViewById(R.id.Body2));
    	evenPage.setProfileImageColor(getString(R.string.top_background)); 
    	oddPage.setCurrent(true);
    	evenPage.setCurrent(false);        	
    }
    
    /* Extract messages & update page */
    private static final int FIRST = 0;
    private static final int NEXT = 1;
    private static final int PREVIOUS = 2;

    private Cursor c;
    
    private Bitmap getPhoto(ContentResolver contentResolver, Long contactId) 
    {	    
    	Uri contactPhotoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);	    
    	InputStream photoDataStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver,contactPhotoUri); 	    
    	Bitmap photo = BitmapFactory.decodeStream(photoDataStream);	    
    	return photo;	
    }
    
    private void showPage(int direction)
    {
    	boolean bResult = false; 	
    	if(direction == FIRST)
    	{
    		c = getContentResolver().query(Uri.parse("content://sms/inbox"),null, null, null, null);
    		bResult = c.moveToFirst();
    		if(bResult == false)
    		{
    			getCurrentPage().updateView(null, null, null, null,null);
    			return;
    		}
    	}
    	else if(direction == NEXT)
    	{
    		if(c.isFirst() == true)
    		{
    			c.moveToLast();    			
    		}
    		else
    		{
    			c.moveToPrevious();    	    			
    		}
    	}
    	else if(direction == PREVIOUS)  
    	{
    		if(c.isLast() == true)
    		{
    			c.moveToFirst();    			
    		}
    		else
    		{
    			c.moveToNext();
    		}
    	}
    
    Integer totalCount = c.getCount();
    Integer currentIndex = c.getPosition();
    currentIndex = totalCount - currentIndex;
    String order = new String(currentIndex.toString() + "/" + totalCount.toString());
    String sender = null;
    Bitmap bitmap = null;
    
    if(c.getString(c.getColumnIndexOrThrow("person"))!= null)
    {
    	String smsid = c.getString(c.getColumnIndexOrThrow("person"));
    	ContentResolver cr = getContentResolver();   	
		Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
	        if (cur.getCount() > 0) {
			     while (cur.moveToNext()) {
			        	 String contactid = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
			        	 if(contactid.compareTo(smsid) == 0)
			        	 {
			        		 sender = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			        		 long id = cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
			        		 bitmap = getPhoto(cr, id);
			        		 break;
			        	 }
			     }
		    }	
    }
    
    if(sender == null){
		String phoneNumber =  c.getString(c.getColumnIndexOrThrow("address"));		
		if(phoneNumber.length() > 8)
		{
			sender = new String(phoneNumber.substring(0,3) + "-" + phoneNumber.substring(3,7) + "-" + phoneNumber.substring(7));
		}
		else if(phoneNumber.length() > 4)
		{
			sender = new String(phoneNumber.substring(0,3) + "-" + phoneNumber.substring(3));			
		}
		else
		{
			sender = phoneNumber;
		}    	
    }
    
    String strDate = DateUtils.getRelativeTimeSpanString(
    		Long.parseLong(c.getString(c.getColumnIndexOrThrow("date"))), 
    		System.currentTimeMillis(), 
    		0, 
    		DateUtils.FORMAT_ABBREV_RELATIVE).toString();
    
    if(direction == FIRST)
    {
    	getCurrentPage().updateView(bitmap, order, strDate, sender, c.getString(c.getColumnIndexOrThrow("body")));
    }
    else
    {
    	goToNextPage().updateView(bitmap, order, strDate, sender, c.getString(c.getColumnIndexOrThrow("body")));
    	if(direction == NEXT)
    	{
    		shiftToRight();
    	}
    	else if(direction == PREVIOUS)
    	{
    		shiftToLeft();
    	}
    }
}
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gestureScanner = new GestureDetector(this);
        setContentView(R.layout.smsviewer);
        flipper = (ViewFlipper)findViewById(R.id.flipper);  
        initializePages();
        showPage(FIRST);
    }
}